import json

MIRROR_FLIP = False

LED_RGB = [255, 255, 255]
LED_STATUS = False

WIFI_NAME = None
WIFI_PWD = None

AP_NAME = 'ESP32S3_N16R8'
AP_PWD = None

CONF_PATH = "/config/conf.json"

SYSTEM_VERSION = "v1.0.0b"
DEVICE_NAME = "ESP32S3_N16R8"

SERVER_API = None
WEATHER_LOC = None
WEATHER_CITY = None
SECRET_ID = None
SECRET_KEY = None

BIRTHDAY_DATE = None

IP = ()


def load_conf(path=CONF_PATH):
    global MIRROR_FLIP, LED_RGB, LED_STATUS, WIFI_NAME, WIFI_PWD, AP_NAME, AP_PWD, DEVICE_NAME, SERVER_API, SECRET_ID, SECRET_KEY, WEATHER_LOC, WEATHER_CITY, BIRTHDAY_MESSAGE, BIRTHDAY_DATE
    with open(path, "r", encoding="utf-8") as fp:
        conf = json.load(fp)
        if conf.get("mirror_flip") is not None:
            MIRROR_FLIP = conf["mirror_flip"]

        WIFI_NAME = conf['wifi'].get("name")
        WIFI_PWD = conf['wifi'].get("pwd")
        AP_NAME = conf['ap'].get("name")
        AP_PWD = conf['ap'].get("pwd")
        SERVER_API = conf.get("server_api")
        SECRET_ID = conf.get("secret_id")
        SECRET_KEY = conf.get("secret_key")

        BIRTHDAY_DATE = conf.get("birthday_date")

        if conf.get("name"):
            DEVICE_NAME = conf["name"]

        if conf.get("weather"):
            WEATHER_LOC = conf["weather"].get("loc")
            WEATHER_CITY = conf["weather"].get("city")

        if conf.get("led"):
            if conf["led"].get("status"):
                LED_STATUS = conf["led"]["status"]
            if conf["led"].get("rgb"):
                LED_RGB = conf["led"]["rgb"]


def save_conf(path=CONF_PATH):
    with open(path, "r", encoding="utf-8") as fp:
        conf = json.load(fp)
        conf.update({
            "mirror_flip": MIRROR_FLIP,
            "led": {
                "status": LED_STATUS,
                "rgb": LED_RGB
            },
            "wifi": {
                "name": WIFI_NAME,
                "pwd": WIFI_PWD
            },
            "ap": {
                "name": AP_NAME,
                "pwd": AP_PWD
            },
            "secret_id": SECRET_ID,
            "secret_key": SECRET_KEY,
            "server_api": SERVER_API,
            "weather": {
                "loc": WEATHER_LOC,
                "city": WEATHER_CITY
            },
            "birthday_date": BIRTHDAY_DATE,
        })
    with open(path, "w", encoding="utf-8") as fp:
        json.dump(conf, fp)
